//
//  KLBookScannerController.m
//  KLBookStore
//
//  Created by apple on 2017/10/14.
//  Copyright © 2017年 NetEaseExam. All rights reserved.
//

#import "KLBookScannerController.h"

#import "KLScannerView.h"
#import "KLAVManager.h"
#import "KLBookEntity.h"
#import "KLBookDetailController.h"

#import "KLBookService.h"

#import <AVFoundation/AVCaptureSession.h>
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import <AVFoundation/AVCaptureInput.h>
#import <AVFoundation/AVCaptureOutput.h>
#import <AVFoundation/AVCaptureVideoPreviewLayer.h>
#import <AVFoundation/AVMetadataObject.h>

#import "AFNetworking.h"

static const CGFloat kScannerRectOffsetY = -43.0f;
static const CGFloat kScannerRectWidth = 230.f;
static NSString *doubanApi = @"https://api.douban.com/v2/book/isbn";

@interface KLBookScannerController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic, strong) KLScannerView *scannerView;
@property (nonatomic, strong) UILabel *scannerTip;
@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, assign, getter=isRunning) BOOL running;

@end

@implementation KLBookScannerController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initSubviews];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    if (self.isRunning == NO) {
        [self.captureSession startRunning];
        self.running = YES;
    }
    if (self.scannerView) {
        [self.scannerView startAnimation];
    }
}

- (void)initSubviews {
    [self initNavItems];
    [self initCamera];
    [self initScannerView];
    [self initTip];
}

- (BOOL)navigationBarShouldShowShadowImage{
    return NO;
}

- (UIImage *)navigationBarBackgroundImage{
    return [UIImage new];
}

- (void)initNavItems{
    //生成一个全透明的导航栏
//    self.navigationController.navigationBar.translucent = YES;
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//    self.navigationController.navigationBar.shadowImage = [UIImage new];
    
    //返回按钮
    UIButton *backBtn = [[UIButton alloc] init];
    [backBtn setImage:[UIImage imageNamed:@"back-button"] forState:UIControlStateNormal];
    [backBtn sizeToFit];
    [backBtn addTarget:self action:@selector(didClickBackButton:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    //手电筒
    UIButton *torchBtn = [[UIButton alloc] init];
    [torchBtn setImage:[UIImage imageNamed:@"light-off"] forState:UIControlStateNormal];
    [torchBtn setImage:[UIImage imageNamed:@"light-on"] forState:UIControlStateSelected];
    [torchBtn sizeToFit];
    
    [torchBtn addTarget:self action:@selector(didClickTorchButton:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:torchBtn];
}

- (void)didClickBackButton: (UIButton *)button{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didClickTorchButton: (UIButton *)button {
    button.selected = !button.selected;
    //开启关闭闪光灯
    if (button.isSelected == YES) { //打开闪光灯
        AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        NSError *error = nil;
        if ([captureDevice hasTorch]) {
            BOOL locked = [captureDevice lockForConfiguration:&error];
            if (locked) {
                captureDevice.torchMode = AVCaptureTorchModeOn;
                [captureDevice unlockForConfiguration];
            }
        }
    }else{//关闭闪光灯
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch]) {
            [device lockForConfiguration:nil];
            [device setTorchMode: AVCaptureTorchModeOff];
            [device unlockForConfiguration];
        }
    }
}


- (void)initCamera {

    self.captureSession = [[AVCaptureSession alloc] init] ;
    [self.captureSession beginConfiguration];

    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //input
    NSError *error = nil;
    AVCaptureDeviceInput *captureInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    
    if (error == nil) {
        if ([self.captureSession canAddInput:captureInput]) {
            [self.captureSession addInput:captureInput];
        }
    }else{
        NSLog(@"Capture Input Error : %@", error);
    }
    
    //output
    AVCaptureMetadataOutput *captureOutput = [[AVCaptureMetadataOutput alloc] init];
    [captureOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    if ([self.captureSession canAddOutput:captureOutput]) {
        [self.captureSession addOutput:captureOutput];
        captureOutput.metadataObjectTypes = @[AVMetadataObjectTypeEAN13Code];
    }
    //add show layer
    CALayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
    previewLayer.frame = self.view.layer.bounds;
    [self.view.layer addSublayer:previewLayer];
    
    [self.captureSession commitConfiguration];
    
    if (self.isRunning == NO) {
        [self.captureSession startRunning];
        self.running = YES;
    }
}

- (void)initScannerView {
    self.scannerView = [[KLScannerView alloc] initWithFrame:self.view.bounds rectSize:CGSizeMake(kScannerRectWidth, kScannerRectWidth) offsetY:kScannerRectOffsetY];
    self.scannerView.backgroundColor = [UIColor clearColor];
    self.scannerView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.scannerView];
    
    [self.scannerView startAnimation];
}

- (void)initTip {
    self.scannerTip = [[UILabel alloc] init];
    self.scannerTip.frame = CGRectMake(self.view.center.x-150, self.view.center.y+kScannerRectWidth*0.5+30+kScannerRectOffsetY, 300, 40);
    self.scannerTip.textAlignment = NSTextAlignmentCenter;
    self.scannerTip.text = @"将条形码放入输入框内，即可自动扫描";
    self.scannerTip.textColor = [UIColor whiteColor];
    self.scannerTip.font = [UIFont systemFontOfSize:15.0];
    
    [self.view addSubview:self.scannerTip];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - ISBN Recgnizer
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    NSString *ISBN = nil;
    for (AVMetadataObject *obj in metadataObjects) {
        ISBN = [(AVMetadataMachineReadableCodeObject *)obj stringValue];
        break;
    }
    
    if (ISBN != nil) {
        NSLog(@"ISBN: %@",ISBN);
        
        [self.captureSession stopRunning];
        [self.scannerView stopAnimation];
        self.scannerTip.text = @"ISBN识别成功";
        
        [self fetchBookWithISBN:ISBN];
        
    } else {
        NSLog(@"Fail to recognize ISBN");
    }
}

- (void)fetchBookWithISBN: (NSString *)ISBN {
    
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",doubanApi,ISBN]];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (error != nil) {
            NSLog(@"Query douban error: %@",error);
        } else{
            NSLog(@"%@,%@",response,responseObject);
            
            NSString *showInfo = nil;
            
            NSString *title = [responseObject objectForKey:@"title"];
            NSArray *authorList = [responseObject objectForKey:@"auther"];
            NSString *author = nil;
            if (authorList.count>0) {
                author = authorList.firstObject;
                showInfo = [NSString stringWithFormat:@"%@\n%@\n%@",title,ISBN,author];
            }else{
                showInfo = [NSString stringWithFormat:@"%@\n%@",title,ISBN];
            }
            
            KLBookEntity *book = [[KLBookEntity alloc] initWithDictionary:responseObject];
            
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:showInfo preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *detailAct = [UIAlertAction actionWithTitle:@"查看详情" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                KLBookDetailController *detailVc = [[KLBookDetailController alloc] init];
                detailVc.bookEntity = book;
                [self.navigationController pushViewController:detailVc animated:YES];
                
                self.running = NO;
                self.scannerTip.text = @"将条形码放入输入框内，即可自动扫描";
            }];
            [alertVc addAction:detailAct];
            
            //判断是否已经收藏
            KLBookEntity *favoredBook = [KLBookService searchFavoredBookWithDoubanId:book.doubanId];
            
            if (favoredBook == nil) {
                UIAlertAction *nextAct = [UIAlertAction actionWithTitle:@"收藏并继续扫描" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    long long bookId = [KLBookService favorBook:book];
                    if (bookId > 0) {
                        
                        NSNotification *notification =[NSNotification notificationWithName:@"FavorBookNotification" object:nil userInfo:nil];
                        [[NSNotificationCenter defaultCenter] postNotification:notification];
                        
                    }

                    [self.captureSession startRunning];
                    [self.scannerView startAnimation];
                    self.scannerTip.text = @"将条形码放入输入框内，即可自动扫描";
                }];
                [alertVc addAction:nextAct];
            }
            
            UIAlertAction *cancelAct = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [self.captureSession startRunning];
                [self.scannerView startAnimation];
                self.scannerTip.text = @"将条形码放入输入框内，即可自动扫描";
            }];
            [alertVc addAction:cancelAct];
            
            [self presentViewController:alertVc animated:YES completion:nil];
        }
    }];
    
    [dataTask resume];
    
}

- (void)dealloc {
    [self.captureSession stopRunning];
    self.running = NO;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
